<?php
//生成图像缩略图和生成验证码
class Image {
	//生成图像验证码
    static public function buildImageVerify($width=48,$height=22,$randval=NULL,$verifyName='verify') {
		if( !isset($_SESSION) ) {
			session_start();//如果没有开启，session，则开启session
		}		
		$randval =empty($randval)? ("".rand(1000,9999)):$randval;
		$_SESSION[$verifyName]= $randval;
		$length=4;
		$width = ($length*10+10)>$width?$length*10+10:$width;
		$im = imagecreate($width,$height);  
		$r = array(225,255,255,223);
		$g = array(225,236,237,255);
		$b = array(225,236,166,125);
		$key = mt_rand(0,3);
		
		$backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);    //背景色（随机）
		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
		$pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
		
		@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
		@imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
		$stringColor = imagecolorallocate($im,mt_rand(0,200),mt_rand(0,120),mt_rand(0,120));
		// 干扰
		for($i=0;$i<10;$i++){
			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
		}
		for($i=0;$i<25;$i++){
			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
		}
		for($i=0;$i<$length;$i++) {
			imagestring($im,5,$i*10+5,mt_rand(1,8),$randval{$i}, $stringColor);
		}
		self::output($im,'png');
    }
	
	//生成缩略图
    static public function thumb($image, $thumbname, $domain = 'public/', $maxWidth=200, $maxHeight=50, $interlace=true) {
        // 获取原图信息
		$info  = self::getImageInfo($image);
		if($info !== false) {
			$srcWidth  = $info['width'];
			$srcHeight = $info['height'];
			$type = strtolower($info['type']);
			$interlace  =  $interlace? 1:0;
			unset($info);
			$scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例
			if($scale>=1) {  // 超过原图大小不再缩略
				$width   =  $srcWidth;
				$height  =  $srcHeight;
			} else {  // 缩略图尺寸
				$width  = (int)($srcWidth*$scale);
				$height = (int)($srcHeight*$scale);
			}
			
			//sae平台上图片处理
			if( class_exists('SaeStorage')) {
				$saeStorage = new SaeStorage();
				$saeImage = new SaeImage();
				$saeImage->setData( file_get_contents($image) );
				$saeImage->resize($width, $height);
				$thumbname = str_replace(array('../', './'), '', $thumbname);
				return $saeStorage->write( $domain, $thumbname, $saeImage->exec() );
			}	
				
			// 载入原图
			$createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
			$srcImg     = $createFun($image);
			
			//创建缩略图
			if($type!='gif' && function_exists('imagecreatetruecolor')) {
				$thumbImg = imagecreatetruecolor($width, $height);
			} else {
				$thumbImg = imagecreate($width, $height);
			}
			// 复制图片
			if(function_exists("ImageCopyResampled")) {
				imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth,$srcHeight);
			} else {
				imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height,  $srcWidth,$srcHeight);
			}	
			if('gif'==$type || 'png'==$type) {
				$background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色
				imagecolortransparent($thumbImg,$background_color);  //  设置为透明色，若注释掉该行则输出绿色的图
			}
			// 对jpeg图形设置隔行扫描
			if('jpg'==$type || 'jpeg'==$type) {
				 imageinterlace($thumbImg,$interlace);
			}
			$dir = dirname($thumbname);
			if ( !is_dir($dir) ) {
				@mkdir($dir, 0777, true);
			}
			// 生成图片
			$imageFun = 'image'.($type=='jpg'?'jpeg':$type);
			$imageFun($thumbImg,$thumbname);
			imagedestroy($thumbImg);
			imagedestroy($srcImg);
			return $thumbname;
         }
         return false;
    }


    static function imgcut($image, $thumbname, $domain = 'public/', $maxWidth = 200, $maxHeight = 50, $interlace = true)
    {
    // 获取原图信息
    $info  = self::getImageInfo($image);
    if($info !== false) {
        $srcWidth  = $info['width'];
        $srcHeight = $info['height'];
        $type = strtolower($info['type']);
        $interlace  =  $interlace? 1:0;
        unset($info);
        $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
        $dst_scale = $maxHeight / $maxWidth; //目标图像长宽比
        $src_scale = $srcHeight / $srcWidth; // 原图长宽比
        if ($src_scale >= $dst_scale) { // 过高
            $w = intval($srcWidth);
            $h = intval($dst_scale * $w);
            $x = 0;
            $y = ($srcHeight - $h) / 3;
        } else { // 过宽
            $h = intval($srcHeight);
            $w = intval($h / $dst_scale);
            $x = ($srcWidth - $w) / 2;
            $y = 0;
        }
        if ($scale >= 1) {
            // 超过原图大小不再缩略
            $width = $srcWidth;
            $height = $srcHeight;
        } else {
            // 缩略图尺寸
            $scale = $maxWidth / $w;
            $width = intval($w * $scale);
            $height = intval($h * $scale);
        }

        //sae平台上图片处理
			if( class_exists('SaeStorage')) {
				$saeStorage = new SaeStorage();
				$saeImage = new SaeImage();
				$saeImage->setData( file_get_contents($image) );
				$saeImage->resize($width, $height);
				$thumbname = str_replace(array('../', './'), '', $thumbname);
				return $saeStorage->write( $domain, $thumbname, $saeImage->exec() );
			}
			
        // 载入原图
        $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
        $srcImg = $createFun($image);
        //创建缩略图
        if ($type != 'gif' && function_exists('imagecreatetruecolor'))
            $thumbImg = imagecreatetruecolor($width, $height);
        else
            $thumbImg = imagecreate($width, $height);
        // 复制图片
        if (function_exists("ImageCopyResampled")) {
            imagecopyresampled($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $w, $h);
        } else {
            imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
        }

        if ('gif' == $type || 'png' == $type) {
            $background_color = imagecolorallocate($thumbImg, 0, 255, 0); //  指派一个绿色
            imagecolortransparent($thumbImg, $background_color); //  设置为透明色，若注释掉该行则输出绿色的图
        }
        // 对jpeg图形设置隔行扫描
        if ('jpg' == $type || 'jpeg' == $type)
            imageinterlace($thumbImg, $interlace);
        // 生成图片
        $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
        $imageFun($thumbImg, $thumbname);
        imagedestroy($thumbImg);
        imagedestroy($srcImg);
        return $thumbname;
    }
    return false;

    }
	
     /**
     * 图片水印
     * @$image  原图
     * @$water 水印图片
     * @$$waterPos 水印位置(0-9) 0为随机，其他代表上中下9个部分位置
     */
    static public function water($image, $water, $waterPos =9) {
	    //检查图片是否存在
        if (!file_exists($image) || !file_exists($water))
            return false;
	   //读取原图像文件
        $imageInfo = self::getImageInfo($image);
        $image_w = $imageInfo['width']; //取得水印图片的宽
        $image_h = $imageInfo['height']; //取得水印图片的高
        $imageFun = "imagecreatefrom" . $imageInfo['type'];
        $image_im = $imageFun($image);
        
        //读取水印文件
        $waterInfo = self::getImageInfo($water);
        $w = $water_w = $waterInfo['width']; //取得水印图片的宽
        $h = $water_h = $waterInfo['height']; //取得水印图片的高
        $waterFun = "imagecreatefrom" . $waterInfo['type'];
        $water_im = $waterFun($water);

        switch ($waterPos) {
            case 0: //随机
                $posX = rand(0, ($image_w - $w));
                $posY = rand(0, ($image_h - $h));
                break;
            case 1: //1为顶端居左
                $posX = 0;
                $posY = 0;
                break;
            case 2: //2为顶端居中
                $posX = ($image_w - $w) / 2;
                $posY = 0;
                break;
            case 3: //3为顶端居右
                $posX = $image_w - $w;
                $posY = 0;
                break;
            case 4: //4为中部居左
                $posX = 0;
                $posY = ($image_h - $h) / 2;
                break;
            case 5: //5为中部居中
                $posX = ($image_w - $w) / 2;
                $posY = ($image_h - $h) / 2;
                break;
            case 6: //6为中部居右
                $posX = $image_w - $w;
                $posY = ($image_h - $h) / 2;
                break;
            case 7: //7为底端居左
                $posX = 0;
                $posY = $image_h - $h;
                break;
            case 8: //8为底端居中
                $posX = ($image_w - $w) / 2;
                $posY = $image_h - $h;
                break;
            case 9: //9为底端居右
                $posX = $image_w - $w;
                $posY = $image_h - $h;
                break;
            default: //随机
                $posX = rand(0, ($image_w - $w));
                $posY = rand(0, ($image_h - $h));
                break;
        }
        //设定图像的混色模式        
        imagealphablending($image_im, true);
        imagecopy($image_im, $water_im, $posX, $posY, 0, 0, $water_w, $water_h); //拷贝水印到目标文件
        //生成水印后的图片
        $bulitImg = "image" . $imageInfo['type'];
        $bulitImg($image_im, $image);
        //释放内存
        $waterInfo = $imageInfo = null;
        imagedestroy($image_im);
    }

    static protected function getImageInfo($img) {
        $imageInfo = getimagesize($img);
        if( $imageInfo!== false) {
            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1));
            $imageSize = filesize($img);
            $info = array(
                "width"=>$imageInfo[0],
                "height"=>$imageInfo[1],
                "type"=>$imageType,
                "size"=>$imageSize,
                "mime"=>$imageInfo['mime']
            );
            return $info;
        } else {
            return false;
        }
    }
	
    static protected function output($im,$type='png',$filename='') {
		header("Content-type: image/".$type);
		$ImageFun='image'.$type;
		if(empty($filename)) {
			$ImageFun($im);
		}else{
			$ImageFun($im,$filename);
		}
		imagedestroy($im);
		exit;
    }
}

if (!function_exists('ImageCreateFrombmp')) { function ImageCreateFrombmp($filename) {
	// version 1.00
	if (!($fh = fopen($filename, 'rb'))) {
		trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
		return false;
	}
	// read file header
	$meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
	// check for bitmap
	if ($meta['type'] != 19778) {
		trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
		return false;
	}
	// read image header
	$meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
	// read additional 16bit header
	if ($meta['bits'] == 16) {
		$meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
	}
	// set bytes and padding
	$meta['bytes'] = $meta['bits'] / 8;
	$meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4)- floor($meta['width'] * $meta['bytes'] / 4)));
	if ($meta['decal'] == 4) {
		$meta['decal'] = 0;
	}
	// obtain imagesize
	if ($meta['imagesize'] < 1) {
		$meta['imagesize'] = $meta['filesize'] - $meta['offset'];
		// in rare cases filesize is equal to offset so we need to read physical size
		if ($meta['imagesize'] < 1) {
			$meta['imagesize'] = @filesize($filename) - $meta['offset'];
			if ($meta['imagesize'] < 1) {
				trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
				return false;
			}
		}
	}
	// calculate colors
	$meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
	// read color palette
	$palette = array();
	if ($meta['bits'] < 16) {
		$palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
		// in rare cases the color value is signed
		if ($palette[1] < 0) {
			foreach ($palette as $i => $color) {
				$palette[$i] = $color + 16777216;
			}
		}
	}
	// create gd image
	$im = imagecreatetruecolor($meta['width'], $meta['height']);
	$data = fread($fh, $meta['imagesize']);
	$p = 0;
	$vide = chr(0);
	$y = $meta['height'] - 1;
	$error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
	// loop through the image data beginning with the lower left corner
	while ($y >= 0) {
		$x = 0;
		while ($x < $meta['width']) {
			switch ($meta['bits']) {
				case 32:
				case 24:
					if (!($part = substr($data, $p, 3))) {
						trigger_error($error, E_USER_WARNING);
						return $im;
					}
					$color = unpack('V', $part . $vide);
					break;
				case 16:
					if (!($part = substr($data, $p, 2))) {
						trigger_error($error, E_USER_WARNING);
						return $im;
					}
					$color = unpack('v', $part);
					$color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
					break;
				case 8:
					$color = unpack('n', $vide . substr($data, $p, 1));
					$color[1] = $palette[ $color[1] + 1 ];
					break;
				case 4:
					$color = unpack('n', $vide . substr($data, floor($p), 1));
					$color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
					$color[1] = $palette[ $color[1] + 1 ];
					break;
				case 1:
					$color = unpack('n', $vide . substr($data, floor($p), 1));
					switch (($p * 8) % 8) {
						case 0:
							$color[1] = $color[1] >> 7;
							break;
						case 1:
							$color[1] = ($color[1] & 0x40) >> 6;
							break;
						case 2:
							$color[1] = ($color[1] & 0x20) >> 5;
							break;
						case 3:
							$color[1] = ($color[1] & 0x10) >> 4;
							break;
						case 4:
							$color[1] = ($color[1] & 0x8) >> 3;
							break;
						case 5:
							$color[1] = ($color[1] & 0x4) >> 2;
							break;
						case 6:
							$color[1] = ($color[1] & 0x2) >> 1;
							break;
						case 7:
							$color[1] = ($color[1] & 0x1);
							break;
					}
					$color[1] = $palette[ $color[1] + 1 ];
					break;
				default:
					trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
					return false;
			}
			imagesetpixel($im, $x, $y, $color[1]);
			$x++;
			$p += $meta['bytes'];
		}
		$y--;
		$p += $meta['decal'];
	}
	fclose($fh);
	return $im;
}}

if (!function_exists('imagebmp')) { function imagebmp($thumbImg, $thumbname) {
    $rs = imagejpeg($thumbImg, $thumbname);
    return $rs;
}}
?>